package com.ll.beautymall.ui.home.indexfragment.view;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.ll.beautymall.R;
import com.ll.beautymall.adapter.CategoryAdapter;
import com.ll.beautymall.adapter.ContentGvAdapter;
import com.ll.beautymall.adapter.ModelAdapter;
import com.ll.beautymall.adapter.PicassoImageLoader;
import com.ll.beautymall.api.UrlConfig;
import com.ll.beautymall.base.BaseFragment;
import com.ll.beautymall.bean.Banner;
import com.ll.beautymall.bean.Category;
import com.ll.beautymall.bean.CategoryList;
import com.ll.beautymall.bean.Content;
import com.ll.beautymall.bean.Floor;
import com.ll.beautymall.bean.HomeAllBuy;
import com.ll.beautymall.bean.ModelContent;
import com.ll.beautymall.ui.home.allbuy.presenter.AllBuyPresenter;
import com.ll.beautymall.ui.home.allbuy.view.IAllBuyView;
import com.ll.beautymall.ui.home.categorydetail.view.CategoryDetailActivity;
import com.ll.beautymall.ui.home.indexfragment.presenter.HeaderPresenter;
import com.ll.beautymall.utils.NetUtil;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 * 每个导航对应的详情的Fragment
 */
public class ContentFragment extends BaseFragment implements IContentView, IAllBuyView {


    @BindView(R.id.xrv)
    XRecyclerView xRecyclerView;


    private HeaderPresenter headerPresenter;
    private Floor mFloor;
    private ContentGvAdapter gvAdapter;
    private com.youth.banner.Banner banner;
    private ModelAdapter modelAdapter;
    private ListView lvModel;
    private CategoryAdapter categoryAdapter;
    private AllBuyPresenter allBuyPresenter;
    private HashMap<String, String> paramters;

    private int current_cursor = 0;
    private int next_cursor;
    private int page_count;

    public ContentFragment() {
    }

    public static ContentFragment createFragment(Floor floor) {
        ContentFragment fragment = new ContentFragment();
        Bundle args = new Bundle();
        args.putSerializable("floor", floor);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView(ViewGroup container) {
        Bundle bundle = getArguments();
        mFloor = (Floor) bundle.getSerializable("floor");

        headerPresenter = new HeaderPresenter(this);
        allBuyPresenter = new AllBuyPresenter(this);

        //设置XRecycler
        configXRecyclerView();

        //加载所有数据
        loadData();

        inflateView(container);
    }

    private void configXRecyclerView() {
        RecyclerView.LayoutManager manager = new GridLayoutManager(getFActivity(), 2, GridLayoutManager.VERTICAL, false);
        xRecyclerView.setLayoutManager(manager);

        //有可能xRecycler还没加载出来，设置空视图
        //给GridView设置空视图,怎么不起效?
        ImageView iv_empty = new ImageView(getFActivity());
        iv_empty.setBackgroundResource(R.mipmap.img_begin_05);
        final RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        iv_empty.setLayoutParams(params);
        xRecyclerView.setEmptyView(iv_empty);

        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //下拉刷新，只需重新拉取数据，allbuy
                loadAllBuyData(false, paramters);
                xRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                paramters.put("cursor", String.valueOf(next_cursor));
                loadAllBuyData(true, paramters);//---要传入参数，更新allbuy的数据
                xRecyclerView.loadMoreComplete();
            }
        });

        gvAdapter = new ContentGvAdapter(getFActivity());
        xRecyclerView.setAdapter(gvAdapter);
    }

    private void inflateView(ViewGroup container) {
        //只有首页与其他页面不一样,首页包含3个解析地址
        //判断，分别填充不同的头部
        if (mFloor.getId() != 1) {//非首页
            View otherView = LayoutInflater.from(getFActivity()).inflate(R.layout.home_header_category, container, false);
            GridView categoryGv = (GridView) otherView.findViewById(R.id.gv_category);
            xRecyclerView.addHeaderView(otherView);

            categoryAdapter = new CategoryAdapter();
            categoryGv.setAdapter(categoryAdapter);

            //点击事件
            categoryGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Intent intent = new Intent(getFActivity(), CategoryDetailActivity.class);
                    for (int j = 0; j < mFloor.getContent().size(); j++) {
                        if (TextUtils.equals(mFloor.getContent().get(j).getContent_type(), "category_list")) {
                            //要将此页面的Category传出,还需要Floor
                            Category category = (Category) adapterView.getItemAtPosition(i);
                            intent.putExtra("category", category);
                            Content content = mFloor.getContent().get(j);
                            intent.putExtra("content", content);
                            startActivity(intent);
                        }
                    }
                }
            });
        } else {//首页
            View indexView = LayoutInflater.from(getFActivity()).inflate(R.layout.home_header, container, false);
            banner = (com.youth.banner.Banner) indexView.findViewById(R.id.vp_autoplay);
            lvModel = (ListView) indexView.findViewById(R.id.lv_model);
            xRecyclerView.addHeaderView(indexView);

            modelAdapter = new ModelAdapter(getFActivity());
            lvModel.setAdapter(modelAdapter);
            lvModel.setDivider(null);

            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
            banner.setIndicatorGravity(BannerConfig.CIRCLE_INDICATOR_TITLE);
            banner.isAutoPlay(true);
            banner.setDelayTime(2000);
        }
    }

    private void loadData() {
        if (NetUtil.hasInternet(getFActivity())) {
            for (int i = 0; i < mFloor.getContent().size(); i++) {
                Content content = mFloor.getContent().get(i);
                if (TextUtils.equals("banner_list", content.getContent_type())) {
                    headerPresenter.setBannerData(content.getRequest_paramters());
                } else if (TextUtils.equals("model_list", content.getContent_type())) {
                    headerPresenter.setModelData(content.getRequest_paramters());
                } else if (TextUtils.equals("product_list", content.getContent_type())) {
                    //首次添加数据
                    paramters = content.getRequest_paramters();
                    //是否是一级界面里的
                    paramters.put(UrlConfig.Key.ISONE, "1");
                    paramters.put(UrlConfig.Key.CURSOR, String.valueOf(current_cursor));
                    paramters.put(UrlConfig.Key.COUNT, "40");
                    paramters.put(UrlConfig.Key.SORT, "default");
                    //是否加载更多
                    loadAllBuyData(false, paramters);
                } else if (TextUtils.equals("category_list", content.getContent_type())) {
                    HashMap<String, String> paramters = content.getRequest_paramters();
                    paramters.put(UrlConfig.Key.CURSOR, "0");
                    paramters.put(UrlConfig.Key.COUNT, "40");
                    headerPresenter.setCategoryData(paramters);
                }
            }
        }
    }

    private void loadAllBuyData(boolean isMore, HashMap<String, String> paramters) {
        allBuyPresenter.setAllBuyData(isMore, paramters);
    }

    @Override
    public int getFLayoutId() {
        return R.layout.fragment_content;
    }

    @Override
    public void setBannerData(final List<Banner> list) {
        List<String> images = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String pic_url = list.get(i).getPic_url();
            images.add(pic_url);
        }
        if (images != null && images.size() > 0) {
            banner.setImages(images).setImageLoader(new PicassoImageLoader()).start();
        }

        banner.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(getFActivity(), CategoryDetailActivity.class);
                String url = list.get(position - 1).getUrl();
                intent.putExtra("bannerdetail", url);
                startActivity(intent);
            }
        });
    }

    @Override
    public void setModelData(List<ModelContent> list) {
        modelAdapter.setData(list);
    }

    @Override
    public void setAllBuyData(HomeAllBuy allBuy) {
        page_count = allBuy.getPage_count();
        next_cursor = allBuy.getNext_cursor();
        gvAdapter.clear();
        gvAdapter.setData(allBuy.getProducts());
    }

    @Override
    public void addAllBuyData(HomeAllBuy allBuy) {
        page_count = allBuy.getPage_count();
        next_cursor = allBuy.getNext_cursor();
        gvAdapter.addData(allBuy.getProducts());
    }

    @Override
    public void showErrorMsg(String msg) {
        Toast.makeText(getFActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setCategoryListData(CategoryList categoryList) {
        List<Category> categories = categoryList.getCategories();
        if (categories != null) {
            categoryAdapter.setData(categories);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (banner != null) {
            banner.startAutoPlay();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (banner != null) {
            banner.stopAutoPlay();
        }
    }
}
